import _thread
import pathlib

from service import processService
from service import emService
from utils.common import *
import json
import requests

from service import detService

"""
10000: 执行指令
10001: 本地进程服务器访问失败
10002: 正常终止
10003: 异常终止
11001: 没有找到指令
11002: 打印日志
11003: 本地没有找到资源
"""


def update_process_status_task(values):
    """检查本地进程是否可ping通过，更新状态至数据库"""
    for record in values:
        _id = record["id"]
        _ip = record["ip"]
        _port = record["port"]
        _url = f"http://{_ip}:{_port}"
        _thread.start_new_thread(url_is_reachable, (_url, _id,))
    return None


def start_local_process_task(values):
    """启动本地进程"""
    _id = values["id"]
    _ip = values["ip"]
    _port = values["port"]
    _url = f"http://{_ip}:{_port}/start/" + str(_id)
    _res = requests.get(_url)
    if _res.text != str(_id):
        _res = {
            "code": "10001",
            "msg": f"{_url}本地进程，访问失败，返回结果：{_res.text}",
            "data": []
        }
        return _res
    _res = to_run_det(values, _id, _ip)
    return _res


def to_run_det(values, process_id, process_ip):
    project = values["project"]
    log_id = values["log_id"]
    parent_path = pathlib.Path(".").absolute()
    project_path = parent_path / "project" / f"{project.name}{project.id}"
    if not project_path.is_dir():
        emService.stop_local_process({
            "project": project.id,
            "process": process_id,
        }, log_id)
        return {
            "code": "11003",
            "msg": f"在服务端找不到项目`{project.name}{project.id}`的本地资源，建议在数据表中删除该无效项目",
            "data": []
        }
    det = detService.Det(
        project_path,
        process_ip,
        {
            "project": project.id,
            "process": process_id,
        }, log_id
    )
    det.run()
    return {
        "code": "11002",
        "msg": f"`{project.name}{project.id}`本地进程，已成功启动",
        "data": []
    }


def url_is_reachable(_url, _id):
    try:
        requests.get(_url, timeout=0.2)
        processService.update_process_status(_id, True)
    except requests.exceptions.ConnectionError:
        processService.update_process_status(_id, False)
